package algebra.rewriting.transform;

import algebra.op.AlgebraicOP;
import algebra.op.JoinOP;
import algebra.op.SelectionOP;
import algebra.rewriting.RewriteRule;

@Deprecated
public class IntersectionInsideSelection extends RewriteRule {
	private final AlgebraicOP op;
	private boolean first = false;

	public IntersectionInsideSelection(AlgebraicOP op) {
		this.op = op;
	}

	@Override
	public AlgebraicOP rewrite() {
		JoinOP ip = op.asIntersectionOP();
		SelectionOP sp = null;
		AlgebraicOP other = null;
		if (first) {
			sp = ip.getFirstSubQuery().asSelectionOP();
			other = ip.getSecondSubQuery();
		} else {
			sp = ip.getSecondSubQuery().asSelectionOP();
			other = ip.getFirstSubQuery();
		}
		return new SelectionOP(new JoinOP(sp.getSubquery(), other),
				sp.getSelectionCondition(), sp.getPlanEvalKB());
	}

	@Override
	public boolean applicable() {
		if (op instanceof JoinOP) {
			if (op.asIntersectionOP().getFirstSubQuery() instanceof SelectionOP) {
				first = true;
				return true;
			} else if (op.asIntersectionOP().getSecondSubQuery() instanceof SelectionOP) {
				first = false;
				return true;
			}
		}
		return false;
	}

}
